package com.usian.mongo;

import com.usian.mongo.pojo.ApComment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@SpringBootTest(classes = MongoApplication.class)
@RunWith(SpringRunner.class)
public class test {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存
    @Test
    public void saveTest(){
        for (int i = 0; i < 20; i++) {
            ApComment apComment = new ApComment();
            apComment.setAuthorName("小王");
            apComment.setContent("河南是个很好的城市");
            apComment.setLikes(i);
            mongoTemplate.save(apComment);
        }
    }
    //查询一个
    @Test
    public void saveFindOne(){
        ApComment apComment = mongoTemplate.findById("62df969db989ba38bcd745a4", ApComment.class);
        System.out.println(apComment);
    }

    //条件查询
    @Test
    public void testQuery(){
        Query query = Query.query(Criteria.where("authorName").is("小王").and("likes").lt(10)).limit(5)
                .with(Sort.by(Sort.Direction.DESC,"likes"));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        System.out.println(apComments);
    }
    @Test
    public void updateQuery(){
        Query query = new Query();
        query.addCriteria(Criteria.where("authorName").is("小王").and("likes").is(10));
        Update update = new Update();
        update.set("authorName","小王八");
        update.set("content","aaaaaaa");
        mongoTemplate.updateMulti(query,update,ApComment.class);
        Query query2 = new Query();
        query2.addCriteria(Criteria.where("authorName").is("小王").and("likes").is(11));
        Update update1 = new Update();
        update1.set("authorName","小憨批");
        update1.set("content","hhhhhhh");
        mongoTemplate.updateMulti(query2,update1,ApComment.class);
    }
    @Test
    public void testDel(){
        mongoTemplate.remove(Query.query(Criteria.where("authorName").is("小王八").and("likes").is(10)),ApComment.class);
    }

}
